# -*- coding: utf-8 -*-
from flask import Flask, send_file, jsonify, request
import os
from loguru import logger
import json
import time
from mysql import connect_sql
from work.creat_project import get_site_id      #导用创建项目模块
# from work.SE_run import se_run
from work.SE_login import se_login              #导用登录模块
from work.retry_login import retry_login        #导用重新登录模块
from work.SE_index_bar import index_bar         #导用进度条模块
from work.SE_dele_keys import dele_keys_word    #导用删除关键词模块
from work.export_excel import excel_export      #导用导出表格模块
from work.SE_add_keys import add_key            #导用添加关键词模块
from work.get_10_keys import get_10_keys_word   #导用获取top10关键词模块
from work.SE_recheck_keys import recheck_keys   #导用复查关键词模块
from work.search_site_list import site_id_list  #导用绑定项目列表模块
from work.requests_cookies import ana_cookies   #导用验证cookeis模块
from work.SE_limits import get_limits




app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

account_files = "./user/user_pool.json"
EXCEL_FOLDER = './excel'

def read_account(file_path, user):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        print("目录不存在，正在创建...")
        os.makedirs(directory)
        print(f"已创建目录: {directory}")

    if not os.path.exists(file_path):
        print("文件不存在，正在创建...")
        open(file_path, 'w').close()
        print(f"已创建json文件: {file_path}")

    if os.path.getsize(file_path) == 0:
        data_to_save = []
        print("文件为空")
        new_user = se_login(user)
        if new_user != 0:
            data_to_save.append(new_user)
            with open(file_path, 'w') as file:
                json.dump(data_to_save, file, indent=4)
            return new_user
    else:
        with open(file_path, 'r') as file:
            json_data = json.load(file)

    target_account = user['account']
    matching_account = None
    for account_info in json_data:
        if account_info["account"] == target_account:
            matching_account = account_info
            break
    if matching_account is not None:
        logger.info(f"账号: {target_account} ----> 账号信息已经存在")
    else:
        logger.info(f"账号: {target_account} ----> 未找到指定账号信息")
        new_user = se_login(user)
        if new_user != 0:
            json_data.append(new_user)
            with open(file_path, 'w') as file:
                json.dump(json_data, file, indent=4)
                logger.success(f"账号: {user['account']} ----> 账号信息保存成功")
            matching_account = new_user
    return matching_account

def account_info(account, password):
    return {"account": account, "password": password}

# 增加认证
@app.before_request
def before_request():
    token = request.headers.get('Authorization')
    if token != "SE-python":
        return jsonify({"error": "UnKnow authorized"}), 403

def data_result1(data):
    required_params = ['account', 'password', 'company_name']
    for param in required_params:
        if param not in data:
            return param
    return None

def data_result2(data):
    required_params = ['account', 'password', 'company_name', 'company_url']
    for param in required_params:
        if param not in data:
            return param
    return None

def data_result3(data):
    required_params = ['account', 'password']
    for param in required_params:
        if param not in data:
            return param
    return None

def str_result1(account, password, company_name):
    if not all([account, password, company_name]):
        missing_param = [param for param, value in {'account': account, 'password': password, 'company_name': company_name}.items() if not value]
        return missing_param[0] if missing_param else None
    return None

def str_result2(account, password):
    if not all([account, password]):
        missing_param = [param for param, value in {'account': account, 'password': password}.items() if not value]
        return missing_param[0] if missing_param else None
    return None

#获取excel文件
@app.route('/SE/get_excel', methods=['GET'])
def get_excel():
    data = request.args.get("company_name")
    EXCEL_FILENAME = data + '.xlsx'
    try:
        file_path = os.path.join(EXCEL_FOLDER, EXCEL_FILENAME)
        # 检查文件是否存在
        if os.path.isfile(file_path):
            return send_file(file_path, as_attachment=True)
        else:
            response = jsonify({"error": "File not found"}), 404
            # response.headers['Content-Type'] = 'application/json; charset=utf-8'
            return response
    except Exception as e:
        return jsonify({"error": str(e)}), 500



@app.route('/SE/cookies', methods=['GET'])
def cookies_true():
    account = request.args.get('account')
    password = request.args.get('password')
    missing_param = str_result2(account, password)
    if missing_param:
        response = jsonify({'error': f'缺乏{missing_param}参数,请重新确认'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    user = account_info(account, password)
    matching_user = read_account(file_path=account_files, user=user)
    if matching_user is None:
        response = jsonify({'error': f"账号: {account} -----> 当前账号密码错误或者不存在该账号"}), 404
        return response
    cookies = matching_user['cookies']
    res = ana_cookies(cookies=cookies)
    if res == 1:
        response = jsonify({'msg': f'账号: {account} 当前cookies信息有效'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    else:
        response = jsonify({'error': f'账号: {account} 当前cookies信息失效'}), 403
        # response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

@app.route('/SE/limits', methods=['GET'])
def Se_limits():
    account = request.args.get('account')
    password = request.args.get('password')
    company_name = request.args.get('company_name')

    missing_param = str_result1(account, password, company_name)
    if missing_param:
        response = jsonify({'error': f'缺乏{missing_param}参数,请重新确认'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    company_info = {
        "company_name": company_name,
    }
    user = account_info(account, password)
    matching_user = read_account(file_path=account_files, user=user)
    if matching_user is None:
        response = jsonify({'error': f"账号: {account} -----> 当前账号密码错误或者不存在该账号"}), 404
        return response
    res = get_limits(company_info=company_info, matching_account=matching_user)
    if res != 0:
        response = jsonify({"msg": f"账号: {matching_user['account']} 限制如下: {res}"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    else:
        response = jsonify({"error": f"账号: {matching_user['account']} 查询关键词限制失败"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

#运行指定账号获取相关项目的excel表格
@app.route('/SE/export_excel', methods=['GET'])
def excel_post():
    account = request.args.get('account')
    password = request.args.get('password')
    company_name = request.args.get('company_name')

    missing_param = str_result1(account, password, company_name)
    if missing_param:
        response = jsonify({'error': f'缺乏{missing_param}参数,请重新确认'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    company_info = {
        "company_name": company_name,
    }
    user = account_info(account, password)
    matching_user = read_account(file_path=account_files, user=user)
    if matching_user is None:
        response = jsonify({'error': f"账号: {account} -----> 当前账号密码错误或者不存在该账号"}), 404
        return response

    res = excel_export(user=matching_user, company_info=company_info)
    if res == 1:
        logger.info(f"账号: {matching_user['account']}: {company_info['company_name']} ----> 导出excel表格成功")
        response = jsonify({"msg": f"账号: {matching_user['account']}: {company_info['company_name']} ----> 导出excel表格成功"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    else:
        logger.info(f"账号: {matching_user['account']}: {company_info['company_name']} ----> 导出excel表格失败")
        response = jsonify({"error": f"{matching_user['account']}: {company_info['company_name']} ----> 导出excel表格失败"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

#复查指定账号的项目关键词
@app.route('/SE/recheck_keys', methods=['GET'])
def get_recheck_keys():
    account = request.args.get('account')
    password = request.args.get('password')
    company_name = request.args.get('company_name')

    missing_param = str_result1(account, password, company_name)
    if missing_param:
        response = jsonify({'error': f'缺乏{missing_param}参数,请重新确认'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    company_info = {
        "company_name": company_name,
    }
    user = account_info(account, password)
    matching_user = read_account(file_path=account_files, user=user)
    if matching_user is None:
        response = jsonify({'error': f"账号: {account} -----> 当前账号密码错误或者不存在该账号"}), 404
        return response
    res = recheck_keys(company_info=company_info, user=matching_user)
    if res == 1:
        response = jsonify({"msg": f"账号: {matching_user['account']}: {company_info['company_name']} 复查中, 请稍后重新查询进度条"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    else:
        response = jsonify({"error": f"账号: {matching_user['account']}: {company_info['company_name']} 复查失败"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

#删除指定账号的指定项目的关键词
@app.route('/SE/dele_keys', methods=['GET'])
def get_dele_keys():
    account = request.args.get('account')
    password = request.args.get('password')
    company_name = request.args.get('company_name')

    missing_param = str_result1(account, password, company_name)
    if missing_param:
        response = jsonify({'error': f'缺乏{missing_param}参数,请重新确认'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    company_info = {
        "company_name": company_name,
    }
    user = account_info(account, password)
    matching_user = read_account(file_path=account_files, user=user)
    if matching_user is None:
        response = jsonify({'error': f"账号: {account} -----> 当前账号密码错误或者不存在该账号"}), 404
        return response
    dele_res = dele_keys_word(company_info=company_info, user=matching_user)
    if dele_res == 1:
        response = jsonify({"msg": f"账号 {matching_user['account']}: {company_info['company_name']} -----> 删除关键词成功"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    elif dele_res == 2:
        response = jsonify({"error": f"账号 {matching_user['account']}: {company_info['company_name']} -----> 没有关键词需要删除"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    else:
        response = jsonify({"error": f"账号 {matching_user['account']}: {company_info['company_name']} -----> 删除关键词失败"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

#运行指定账号查看项目
@app.route('/SE/project', methods=['GET'])
def project_list():
    account = request.args.get('account')
    password = request.args.get('password')
    company_name = request.args.get('company_name')

    missing_param = str_result2(account, password)
    if missing_param:
        response = jsonify({'error': f'缺乏{missing_param}参数,请重新确认'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    company_info = {
        "company_name": company_name,
    }
    user = account_info(account, password)
    matching_user = read_account(file_path=account_files, user=user)
    if matching_user is None:
        response = jsonify({'error': f"账号: {account} -----> 当前账号密码错误或者不存在该账号"}), 404
        return response
    cookies = matching_user['cookies']
    res = site_id_list(cookies=cookies)
    if res != 0:
        response = jsonify({'msg': res})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    elif res == -1:
        response = jsonify({'error': f'账号: {account} cookies信息已失效'}), 403
        return response
    else:
        response = jsonify({'error': f'账号: {account} 没有查询到项目'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

#运行指定账号查看相关项目的进度条
@app.route('/SE/index_bar', methods=['GET'])
def search_index_bar():
    account = request.args.get('account')
    password = request.args.get('password')
    company_name = request.args.get('company_name')

    missing_param = str_result1(account, password, company_name)
    if missing_param:
        response = jsonify({'error': f'缺乏{missing_param}参数,请重新确认'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

    company_info = {
        "company_name": company_name,
    }
    user = account_info(account, password)
    matching_user = read_account(file_path=account_files, user=user)
    if matching_user is None:
        response = jsonify({'error': f"账号: {account} -----> 当前账号密码错误或者不存在该账号"}), 404
        return response
    if matching_user == 0:
        response = jsonify({'error': f"账号: {account} -----> 当前账号密码错误或者不存在该账号"}), 404
        return response

    res = index_bar(company_info=company_info, user=matching_user)
    if res == 0:
        response = jsonify({"msg": f"账号: {user['account']} -----> 没有 {company_info['company_name']} 该项目"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    if res == -1:
        response = jsonify({"error": f"{matching_user['account']}: 当前账号的cookies信息失效"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    else:
        query_sql = f"""SELECT tags FROM zxp_domain WHERE remark = '{company_info["company_name"]}'"""
        if res >= 99:
            db = connect_sql()
            cursor = db.cursor()
            cursor.execute(query_sql)
            bid_res = cursor.fetchone()
            if bid_res is None:
                response = jsonify({"error": f"数据库没有查询到 {company_info['company_name']}"})
                response.headers['Content-Type'] = 'application/json; charset=utf-8'
                return response
            top_10_keys = get_10_keys_word(company_info=company_info, user=matching_user)
            if top_10_keys > bid_res[0]:
                logger.info(f"账号: {matching_user['account']}: {company_info['company_name']} 已达标")
                dele_res = dele_keys_word(company_info=company_info, user=matching_user)
                if dele_res == 1:
                    response = jsonify({"msg": f"账号: {matching_user['account']}: {company_info['company_name']} 进度条: {res}, 需达标数: {bid_res[0]} 达标数: {top_10_keys}已达标，且自动删除top100以外关键词"})
                    response.headers['Content-Type'] = 'application/json; charset=utf-8'
                    cursor.close()
                    db.close()
                    return response
                elif dele_res == 2:
                    response = jsonify({"msg": f"账号: {matching_user['account']}: {company_info['company_name']} 进度条: {res}, 需达标数: {bid_res[0]} 达标数: {top_10_keys}已达标，且无需删除关键词"})
                    response.headers['Content-Type'] = 'application/json; charset=utf-8'
                    cursor.close()
                    db.close()
                    return response
                else:
                    response = jsonify({"error": f"{matching_user['account']}: {company_info['company_name']} 删除关键词失败"})
                    response.headers['Content-Type'] = 'application/json; charset=utf-8'
                    cursor.close()
                    db.close()
                    return response
            elif bid_res[0] - 20 < top_10_keys < bid_res[0]:
                response = jsonify({"msg": f"账号: {matching_user['account']}: {company_info['company_name']} 达标标准: {bid_res[0]} 目前达标数: {top_10_keys}, 请选择是否复查"})
                response.headers['Content-Type'] = 'application/json; charset=utf-8'
                cursor.close()
                db.close()
                return response
            else:
                dele_res = dele_keys_word(company_info=company_info, user=matching_user)
                if dele_res == 1:
                    logger.info(f"账号: {matching_user['account']}: {company_info['company_name']} ----> 删除关键词成功")
                    response = jsonify(
                        {"msg": f"账号: {matching_user['account']}: {company_info['company_name']} 当前进度条 ----> {res}, 且已删除成功"})
                    response.headers['Content-Type'] = 'application/json; charset=utf-8'
                    cursor.close()
                    db.close()
                    return response
                elif dele_res == 2:
                    response = jsonify({"msg": f"账号: {matching_user['account']}: {company_info['company_name']} 进度条: {res}, 无需删除关键词"})
                    response.headers['Content-Type'] = 'application/json; charset=utf-8'
                    cursor.close()
                    db.close()
                    return response
                else:
                    response = jsonify({"error": f"账号: {matching_user['account']}: {company_info['company_name']} 删除关键词失败"})
                    response.headers['Content-Type'] = 'application/json; charset=utf-8'
                    cursor.close()
                    db.close()
                    return response
        response = jsonify({"msg": f"账号: {matching_user['account']}: {company_info['company_name']} 当前进度条 ----> {res}"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        # cursor.close()
        # db.close()
        return response

def data_result4(data):
    required_params = ['account', 'password', 'company_name', 'keys_list']
    for param in required_params:
        if param not in data:
            return param
    return None

#运行指定账号添加关键词
@app.route('/SE/add_keys', methods=['POST'])
def SE_run():
    data = request.form
    missing_param = data_result4(data)
    if missing_param:
        response = jsonify({'error': f'缺乏{missing_param}参数,请重新确认'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    company_info = {"company_name": data['company_name']}
    keys_list = data['keys_list'].split(',')

    user = account_info(data["account"], data["password"])
    matching_user = read_account(file_path=account_files, user=user)
    if matching_user is None:
        response = jsonify({'error': f"账号: {data['account']} -----> 当前账号密码错误或者不存在该账号"}), 404
        return response

    res = add_key(keys_word=keys_list, matching_account=matching_user, company_info=company_info)
    if isinstance(res, int):
        response = jsonify({"msg": f"账号: {user['account']}: {company_info['company_name']} 添加 {res}个关键词 成功"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    elif res == 0:
        response = jsonify({"error": f"账号: {user['account']}: {company_info['company_name']} 添加关键词失败"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    else:
        response = jsonify({"msg": f"账号: {user['account']}: {res}"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

#运行指定账号创建项目
@app.route('/SE/creat_project', methods=['POST'])
def creat_project():
    data = request.form
    missing_param = data_result2(data)
    if missing_param:
        response = jsonify({'error': f'缺乏{missing_param}参数,请重新确认'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

    user = account_info(data["account"], data["password"])
    company_info = {
        "company_name": data["company_name"],
        "company_url": data['company_url']
    }

    matching_user = read_account(file_path=account_files, user=user)
    if matching_user is None:
        response = jsonify({'error': f"账号: {data['account']} -----> 当前账号密码错误或者不存在该账号"}), 404
        return response
    cookies = matching_user['cookies']
    res = get_site_id(company_info=company_info, cookies=cookies)
    if res != 0:
        response = jsonify({'msg': f"账号 {user['account']}: 创建 {company_info['company_name']} 项目成功"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    else:
        response = jsonify({'error': f"账号 {user['account']}: 创建 {company_info['company_name']} 项目失败, 疑似cookies信息失效，请确认"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

#重新登录获取cookies信息
@app.route('/SE/retry_login', methods=['POST'])
def api_retry_login():
    data = request.form
    missing_param = data_result3(data)
    if missing_param:
        response = jsonify({'error': f'缺乏{missing_param}参数,请重新确认'})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    user = account_info(data["account"], data["password"])
    res = retry_login(user)
    if res == 1:
        response = jsonify({'msg': f"账号: {user['account']} ----> 更新cookies信息成功"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    else:
        response = jsonify({'error': f"账号: {user['account']} ----> 更新cookies信息失败"})
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response

if __name__ == '__main__':
    app.run(port=8890, debug=True, host='0.0.0.0')